package fun.codedesign.datasource.spring.boot.autoconfigure;

import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class TenantDataSource implements DataSource, Closeable {

    private final Map<String, DataSource> tenantDataSource = new HashMap<>(32);

    @Override
    public void close() throws IOException {
        ((Closeable)proxy()).close();
    }

    public DataSource proxy() {
        return tenantDataSource.get(TenantContextHolder.getTenant());
    }

    @Override
    public Connection getConnection() throws SQLException {
        return proxy().getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return proxy().getConnection(username, password);
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return proxy().getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        proxy().setLogWriter(out);
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        proxy().setLoginTimeout(seconds);
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return proxy().getLoginTimeout();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return proxy().getParentLogger();
    }


    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return proxy().unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return proxy().isWrapperFor(iface);
    }

    public void add(String master, HikariDataSource dataSource1) {
        tenantDataSource.put(master, dataSource1);
    }
}
